package com.hm.service.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EncryptionUtils {
    //定义加密算法
    private static final String Algorithm = "AES/ECB/PKCS5Padding";

    public static String encrypt(String secretKey, String content) {
        try {
            Cipher cipher = Cipher.getInstance(Algorithm);
            //注意如果secretKey是动态的，这里不能写单例模式 必须每次要new
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
            byte[] cipherBytes = cipher.doFinal(contentBytes);
            return Base64.getEncoder().encodeToString(cipherBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String decrypt(String secretKey, String content) {
        try {
            //base64密文解码
            byte[] encrypted = Base64.getDecoder().decode(content);
            Cipher cipher = Cipher.getInstance(Algorithm);
            //注意如果secretKey是动态的，这里不能写单例模式 必须每次要new
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptBytes = cipher.doFinal(encrypted);
            return new String(decryptBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
